<!--
 * @Author: ybf
 * @Date: 2023-02-21 15:31:51
 * @LastEditTime: 2023-12-15 17:33:33
 * @Description: 描述
 * Copyright (c) 2023 by 慧能分享, All Rights Reserved.
-->
<template>
    <div class="dataMonitoring">
        <NuVerifyForm :model="formData" ref="formData" label-width="110px" class="searchForm" @searchForm="searchForm"
            :buttons="fyButtons">
            <NuformItem label="通道组名称" prop="groupName" width="auto">
                <nu-select class="searchSelect" :filterable="true" :list="channelList" type="text" :valueName="'groupName'"
                    :label="'groupName'" v-model="formData.groupName" autocomplete="off" @change="channelChange"
                    style="width: 100%;" placeholder="请选择">
                </nu-select>
            </NuformItem>
            <!-- <NuformItem label="通道名称" prop="channelName" width="auto">
                <nu-select class="searchSelect" :filterable="true" :list="thoroughfareList" type="text"
                    v-model="formData.channelName" autocomplete="off" @change="thoroughfareChange" style="width: 100%;"
                    :valueName="'channelName'" :label="'channelName'" placeholder="请选择">
                </nu-select>
            </NuformItem> -->
            <NuformItem label="关联设备名称" prop="deviceName" width="auto">
                <nu-input type="text" v-model="formData.deviceName" size="medium" placeholder="请输入关联设备名称"></nu-input>
            </NuformItem>
            <NuformItem label="量测名称" prop="meterName" width="auto">
                <nu-input type="text" v-model="formData.meterName" size="medium" placeholder="请输入量测名称"></nu-input>
            </NuformItem>
            <div class="btnBox">
                <nu-button type="primary" class="searchButton" @click="searchTable">搜索</nu-button>
                <nu-button class="searchButton" @click="clearParams">清除</nu-button>
            </div>
        </NuVerifyForm>
        <div class="line"></div>
        <div style="height:35px;position: relative;padding: 0 10px;" class="renovateTime">
            <nu-button class="searchButton" @click="exportTable">导出</nu-button>
            <nu-button class="searchButton" v-print="printOption">打印</nu-button>
            <el-dropdown split-button size="medium" type="primary" @command="handleCommand" @click="renovateTimeClick"
                trigger="click" class="dropdownBtn">
                刷新
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="a">每10s自动刷新</el-dropdown-item>
                    <el-dropdown-item command="b">每20s自动刷新</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
        <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
            :pagination="pagination" @handleSizeChange="handleSizeChange" @handleChangePage="handleChangePage"
            v-loading="tableLoading">
        </NuTableList>
        <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="optionsPrint"
            style="position: absolute;left: -5000px;z-index: -100;opacity: 0;">
        </NuTableList>
    </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue"
import nutbTitle from "@/components/base/tableTitle.vue"
import NuVerifyForm from "@/components/verify-form"
import NuformItem from "@/components/verify-form/form-item.vue"
import nuInput from "@/components/base/input"
import nuSelect from "@/components/base/select"
import nuButton from "@/components/base/button"
import NuTableList from "@/components/tableList/TableFormList"
import nuDialog from "@/components/base/dialog"
import nuSelectTree from "@/components/base/selectTree"

import { getToken } from "@/utils/auth";
import { getDateTime } from "@/utils/ruoyi";
import store from "@/store";
export default {
    name: "dataMonitoring",
    components: { nuCol, nutbTitle, NuVerifyForm, NuformItem, nuInput, nuSelect, nuButton, NuTableList, nuDialog, nuSelectTree },
    data() {
        return {
            formData: {
                groupName: "",
                channelName: "",
                deviceName: "",
                meterName: "",
                dateTime: ''
                // refreshTime: 1
                // startDay: '',
                // endDay: '',
            },
            fyButtons: [],
            pagination: {
                pageSize: 20,
                total: 0,
                pageNum: 1,
            },
            columns: [
                {
                    label: '序号',
                    prop: 'ranking',
                    width: '70px',
                    render: (h, params) => {
                        return h('span', params.index + 1 + (this.pagination.pageNum - 1) * this.pagination.pageSize);
                    },
                },
                {
                    label: '关联设备名称',
                    prop: 'relatedDevName',
                    width: 200
                },
                {
                    label: '量测名称',
                    prop: 'cmdType',
                },
                {
                    label: '点号',
                    prop: 'ioa',
                },
                {
                    label: '当前值',
                    prop: 'cmdValue',
                    render: (h, params) => {

                        if (store && store.getters.sysEnergyType == 'WIND') {
                            if (params.row.cmdValueDesc) {
                                return h('span', params.row.cmdValueDesc);
                            } else {
                                return h('span', params.row.cmdValue);
                            }
                        }
                        if (store && store.getters.sysEnergyType !== 'WIND') {
                           
                            return h('span', params.row.cmdValue);
                        }
                    }
                },
                {
                    label: '单位',
                    prop: 'unit',
                    width: 70
                },
                {
                    label: '通道组名称',
                    prop: 'channelGroupName',
                },
                // {
                //     label: '通道名称',
                //     prop: 'adaptChannelName',
                // },
                {
                    label: '更新时间',
                    prop: 'cmdTime',
                }
            ],
            dataSource: [{}],
            options: {
                'default-expand-all': true,
                'element-loading-background': 'rgba(225,239,242)',
                'element-loading-text': '数据正在加载中',
                'row-key': 'pid',
                'header-cell-style': {
                    background: 'rgba(105, 159, 209, 0.7)',
                    color: '#fff',
                    fontWeight: 'bold',
                    fontsize: '16px',
                },
                height: 'calc(100vh - 310px)',

            },
            optionsPrint: {
                'row-key': 'pid',
                height: '100vh',
                tId: 'multipleTable',
                style: 'width:1000px'
            },
            renovateTime: 10 * 1000,
            renovateTimeInterval: null,
            thoroughfareList: [],
            channelList: [],
            restaurants: [],
            treeData: [],
            // 数据默认字段
            defaultProps: {
                parent: 'parentId',   // 父级唯一标识
                value: 'id',          // 唯一标识
                label: 'label',       // 标签显示
                children: 'children', // 子级
            },
            printOption: {
                id: 'multipleTable',
                preview: true,
                previewTitle: '预览',
                popTitle: '',
                extraHead: '',
                extraCss: `<meta http-equiv='Content-Language' content='zh-cn'/>`,
            },
            tableLoading: false
        };
    },
    computed: {
        dialogFormDisabled() {
            return this.dialogTitle == '详情'
        }
    },
    created() {
    },
    mounted() {
        this.formData.dateTime = getDateTime('day')
        this.handleCommand('a')
        this.getDataMonitoring();
        this.restaurants = this.loadAll();
        // this.getTreeData()
        this.getChannelCondition()
        this.getOneLevelDicts()
    },
    beforeDestroy() {
        if (this.renovateTimeInterval) {
            clearInterval(this.renovateTimeInterval)
        }
    },
    methods: {
        /**
         * 查询
         */
        searchTable() {
            this.$refs['formData'].searchForm('form');
        },
        /**
         * form组件内置查询事件
         */
        searchForm(val) {
            if (val) {
                this.getDataMonitoring();
            }
        },
        /**
         * 每页条数变化事件
         */
        handleSizeChange(val) {
            this.pagination.pageNum = 1;
            this.pagination.pageSize = val;
            this.getDataMonitoring();
        },
        /**
         * 改变分页触发事件
         */
        handleChangePage(val) {
            this.pagination.pageNum = val;
            this.getDataMonitoring();
        },
        /**
         * change事件
         */
        thoroughfareChange() { },
        /**
         * 通道组change事件
         */
        channelChange(val) {
            this.formData.channelName = ''
            let postData = {
                pageNum: 1,
                pageSize: 99999,
                channelName: ""
            };
            this.$httpGet(window.api.getChannelCondition, postData).then(res => {
                if (res.code == 200 && res.rows) {
                    let conditionList = res.rows.filter((item) => {
                        return item.belongGroupName == val
                    })
                    this.thoroughfareList = conditionList
                } else {
                }
            }).catch(err => {

            });
        },

        /**
         * 获取通道组列表
         */
        getChannelCondition() {
            let postData = {
                pageNum: 1,
                pageSize: 99999,
                channelName: ""
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.dataSource = [];

            this.$httpGet(window.api.getChannelGroupSet, postData).then(res => {
                if (res.code == 200 && res.rows) {
                    this.channelList = res.rows

                } else {
                }
            }).catch(err => {

            });
        },

        /**
         * 关联机组类型
         */
        getOneLevelDicts() {
            this.$httpGet(window.api.getOneLevelDicts, { dictType: "RELATED_DEVICE_TYPE", pageSize: 9999, pageNum: 1 }).then(res => {
                if (res.code == 200) {
                    this.nitBusTypeDict = res.rows
                } else {
                }
            }).catch(err => {

            });

        },
        /**
         * 返回输入建议的方法
         * @param {*} queryString 
         * @param {*} cb 
         */
        querySearchAsync(queryString, cb) {
            var restaurants = this.restaurants;
            var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
                cb(results);
            }, 3000 * Math.random());
        },
        /**
         * 过滤数据
         * @param {*} queryString 
         */
        createStateFilter(queryString) {
            return (state) => {
                return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        /**
         * 点击选中建议项时触发
         * @param {*} item 
         */
        handleSelect(item) {
            console.log(item);
        },
        /**
         * 清除数据
         */
        clearParams() {
            this.resetForm('formData')
        },
        /**
         * 重置表单
         */
        resetForm(formName) {
            this.$refs[formName].resetForm('form');
            for (let k in this[formName]) {
                if (Object.prototype.toString.call(this[formName][k]) == "[object String]") {
                    this[formName][k] = ''
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Array]") {
                    this[formName][k] = []
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Number]") {
                    this[formName][k] = ''
                }
            }
        },
        /**
         * 导出
         */
        exportTable() {
            this.getDownload(window.api.exportRealTelemetrys, {
                ...this.formData
            }, `遥测当前数据监视.xlsx`)
            // this.$httpPost(window.api.exportData).then(res => {
            //     if (res.success) {
            //         this.$message({
            //             message: '成功',
            //             type: 'success'
            //         })
            //     } else {
            //     }
            // }).catch(err => {

            // });
        },
        /**
         * 打印
         */
        print() {
            window.print()
        },
        /**
         * 下拉菜单指令
         * @param {*} command 
         */
        handleCommand(command) {
            let timeObj = {
                a: 10 * 1000,
                b: 20 * 1000,
            }
            this.renovateTime = timeObj[command]
            if (this.renovateTimeInterval) {
                clearInterval(this.renovateTimeInterval)
            }
            this.renovateTimeInterval = setInterval(() => {
                this.getDataMonitoring()
            }, this.renovateTime)
        },
        /**
         * 刷新
         */
        renovateTimeClick() {
            this.getDataMonitoring()
        },
        /**
         * 获取表格数据
         */
        getDataMonitoring() {
            let postData = {
                ...this.formData,
                ...this.pagination
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            // this.tableLoading = true
            this.$httpGet(window.api.getRealTelemetrys, postData).then(res => {
                if (res.code == 200) {
                    this.pagination.total = res.total;
                    this.dataSource = res.rows;
                } else {
                }
                // this.tableLoading = false
            }).catch(err => {
                // this.tableLoading = false
            });
        },
        //获取树形控件
        getTreeData() {
            let postData = {
                type: 1
            }
            this.$httpPost(window.api.getTreeData, postData).then(res => {
                if (res.success) {
                    this.treeData = res.data
                } else {
                }
            }).catch(err => {

            });
        },
        // 远程搜索数据
        loadAll() {
            return [
                { "value": "三全鲜食（北新泾店）", "address": "长宁区新渔路144号" },
                { "value": "Hot honey 首尔炸鸡（仙霞路）", "address": "上海市长宁区淞虹路661号" },
                { "value": "新旺角茶餐厅", "address": "上海市普陀区真北路988号创邑金沙谷6号楼113" },
                { "value": "泷千家(天山西路店)", "address": "天山西路438号" },
                { "value": "胖仙女纸杯蛋糕（上海凌空店）", "address": "上海市长宁区金钟路968号1幢18号楼一层商铺18-101" },
                { "value": "贡茶", "address": "上海市长宁区金钟路633号" },
                { "value": "豪大大香鸡排超级奶爸", "address": "上海市嘉定区曹安公路曹安路1685号" },
                { "value": "茶芝兰（奶茶，手抓饼）", "address": "上海市普陀区同普路1435号" },
                { "value": "十二泷町", "address": "上海市北翟路1444弄81号B幢-107" },
                { "value": "星移浓缩咖啡", "address": "上海市嘉定区新郁路817号" },
                { "value": "阿姨奶茶/豪大大", "address": "嘉定区曹安路1611号" },
                { "value": "新麦甜四季甜品炸鸡", "address": "嘉定区曹安公路2383弄55号" },
            ];
        },
    }
};
</script>
<style scoped lang="scss">
.dataMonitoring {
    height: 100%;
}

.searchForm {
    // height: calc(100% - 40px);
    display: flex;
    position: relative;
    padding-right: 160px;
    flex-wrap: wrap;
}

.submitForm {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}

.treeTable {
    display: flex;
}

.btnBox {
    display: flex;
    // float: right;
    z-index: 10;
    position: absolute;
    // top: 15px;
    right: 10px;
    margin: 10px 0 0 0;
}

::v-deep .el-dropdown {
    position: absolute;
    right: 10px;
    top: 2px;
}

::v-deep .el-button--primary {
    background-color: rgba(71, 99, 255, 1);
    border-color: rgba(71, 99, 255, 1);
}

// ::v-deep .el-button--medium{
//     padding: 8px 18px;
// }
.dropdownBtn ::v-deep .el-button-group .el-button--primary {
    height: 32px;
}
</style>
    
    